<script setup name="AuthRole" lang="ts">
import type { RoleVO } from '@/api/system/role/types'
import { getAuthRole, updateAuthRole } from '@/api/system/user'
import type { UserForm } from '@/api/system/user/types'

const props = defineProps({
  userId: {
    type: [String, Number],
  },
})
const emits = defineEmits(['success'])
const roleIds = ref<Array<string | number>>([])
const roles = ref<RoleVO[]>([])
const form = ref<Partial<UserForm>>({
  nickName: undefined,
  userName: '',
  userId: undefined,
})

/** 提交按钮 */
async function submitForm() {
  console.log('验证通过')
  const userId = form.value.userId
  const rIds = roleIds.value.join(',')
  await updateAuthRole({ userId: userId as string, roleIds: rIds })
  emits('success')
}

async function getList() {
  const userId = props.userId
  if (userId) {
    const res = await getAuthRole(userId as string)
    Object.assign(form.value, res.data.user)
    Object.assign(roles.value, res.data.roles)
    await nextTick(() => {
      roles.value.forEach((row) => {
        if (row?.flag)
          roleIds.value.push(row.roleId)
      })
    })
  }
}

onMounted(() => {
  getList()
})

defineExpose({ submitForm })
</script>

<template>
  <div class="p-2">
    <div class="p-20px">
      职员:{{ form.nickName }}
    </div>
    <div class="base-div p-20px">
      <div class="panel-title">
        请选择角色
      </div>
      <a-divider />
      <a-checkbox-group v-model:value="roleIds" class="flex">
        <div style="width: 100%">
          <div>
            <a-row :gutter="20">
              <template v-for="(role) in roles" :key="role.roleId">
                <a-col :span="6" class="mb-10px">
                  <a-checkbox :value="role.roleId">
                    {{ role.roleName }}
                  </a-checkbox>
                </a-col>
              </template>
            </a-row>
          </div>
        </div>
      </a-checkbox-group>
    </div>
  </div>
</template>

<style scoped lang='less'>
  .base-div{
    background: #FCFCFC;
    border-radius: 8px;
  }
</style>
